import store from '../store/index.js'
//是否已经连接上ws
let isOpenSocket = false
//心跳间隔，单位毫秒
let heartBeatDelay = 3000
let heartBeatInterval = null
//心跳时发送的消息文本
let heartBeatText = "ping"
//最大重连次数
let reconnectTimes = 10
let reconnectInterval = null
//重连间隔，单位毫秒
let reconnectDelay = 3000
let isGetMyId = false
let newUserOnline = false
let uidMap = []

let wsUrl = "ws://192.168.31.146:8095/chat/private/chat"

let socketTask = null

let canReconnect = false

//初始化socketTask对象
let ws = { //websocket工具
	socketTask: null,
	init,
	completeClose //完全关闭ws
}

function init() {
	let token = uni.getStorage({
		key:'xdzn_token'
	})
	socketTask = uni.connectSocket({
		url: wsUrl,
		header:{
			xdzn_token: token
		},
		success: (res) => {
			console.log('ws连接创建成功')
		},
		fail: (res) => {
			console.log('ws链接失败', res)
		},
	})
	socketTask.onOpen((res) => {
		console.log("ws连接成功")
		clearInterval(heartBeatInterval)
		clearInterval(reconnectInterval)
		isOpenSocket = true
		canReconnect = true
		//开启心跳
		heartBeat()
	})
	socketTask.onMessage((res) => {
		if(isOpenSocket && isGetMyId){
			console.log(res)
			if(res.data.success){
				//console.log('id已经设置完毕',res)
				
			}
		}else if(isOpenSocket && !isGetMyId){
			store.state.webSocketUtil.fromUser = JSON.parse(res.data).fromUser
			//console.log('获取到了id，正在设置',res)
			console.log(store.state.webSocketUtil.fromUser)
			isGetMyId = true
		}else{
			console.log(res)
		}
		//自定义处理onMessage方法
		//console.log(res)
	})
	socketTask.onClose(() => {
		if(isOpenSocket){
			console.log("ws与服务器断开") 
		}else{
			console.log("连接失败")
		}
		isOpenSocket = false
		isGetMyId = false
		if(canReconnect){
			reconnect()
			canReconnect = false
		}
	})
	ws.socketTask = socketTask
}

function heartBeat() {
	heartBeatInterval = setInterval(() => {
		//console.log(heartBeatText)
		send(JSON.stringify(heartBeatText));
		
	}, heartBeatDelay)
}

function send(value) {
	ws.socketTask.send({
		data: value,
		async success(res) {
			//对 ping 返回的信息进行处理，设置
			uidMap = JSON.parse(res.data)
			newUserOnline = testMap(uidMap)
			if(!newUserOnline){
				uidMap = [] //暂时是List，后面连上飞神的服务器了就转为正经的Map
				return;
			}else{
				if(uidMap.success ){
					if(store.state.webSocketUtil.toUser == ''){
						let me = store.state.webSocketUtil.fromUser
						uidMap.userList.splice(uidMap.userList.indexOf(me), 1)
						store.state.webSocketUtil.toUser = uidMap.userList[0]
					}
				}
				uidMap = []
			}
		}
	});
}

function updateOnlineList(){
	
}


function reconnect() {
	//停止发送心跳
	clearInterval(heartBeatInterval)
	//如果不是人为关闭的话，进行重连
	if (!isOpenSocket) {
		let count = 0;
		reconnectInterval = setInterval(() => {
			console.log("正在尝试重连")
			init();
			count++
			//重连一定次数后就不再重连
			if(count >= reconnectTimes){
				clearInterval(reconnectInterval)
				console.log("网络异常或服务器错误")
			}
		}, reconnectDelay)
	}
}
function completeClose(){
	//清除心跳与重连的定时器
	clearInterval(heartBeatInterval)
	clearInterval(reconnectInterval)
	isGetMyId = false
	canReconnect = false
	ws.socketTask.close()
}

module.exports = ws
